package de.pa2.proxy;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;
import org.apache.commons.vfs.FileListener;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.impl.DefaultFileMonitor;

import de.pa2.proxy.config.ServerConfiguration;

public class Proxy {
	public static void main(String[] args) throws Exception {
		String configFile = System.getProperty("config");
		String resourcesDir = System.getProperty("resources");
		String listen = System.getProperty("listen");

		CustomFileListener listener = new CustomFileListener();

		FileSystemManager fsManager = VFS.getManager();
		FileObject listenFile = fsManager.resolveFile(configFile);

		DefaultFileMonitor fm = new DefaultFileMonitor(listener);
		fm.setRecursive(true);
		fm.addFile(listenFile);
		fm.start();

		String xml = FileUtils.readFileToString(new File(configFile), "UTF8");
		ServerConfiguration configuration = ServerConfiguration.parse(xml);

		Enumeration enu = NetworkInterface.getNetworkInterfaces();
	    while (enu.hasMoreElements()) {
	      NetworkInterface net = (NetworkInterface) enu.nextElement();
	      System.out.println(net);               
	    }
		
		InetAddress address = InetAddress.getLocalHost();

		Thread proxyThread = new ProxyRequestListenerThread(configuration
				.getProxyPort(), configuration);
		proxyThread.setDaemon(false);
		proxyThread.start();

		Thread deadEndThread = new DeadEndHttpServerRequestListenerThread(
				configuration.getDeadEndPort(), address);
		deadEndThread.setDaemon(false);
		deadEndThread.start();

		Thread httpThread = new HttpServerRequestListenerThread(configuration
				.getServerPort(), resourcesDir, configuration);
		httpThread.setDaemon(false);
		httpThread.start();
	}
}
